<!-- WmsPda的主布局，和标准主局主要差别在于:
  1, 标题栏始终显示
  2, 标题栏不显示用户信息和消息，放在左抽屉上显示
  3, 左抽屉上除了显示菜单之外还显示头像等用户信息
  4, 无Footer，无ICP、版本等信息
-->
<template>
  <q-layout view="hhh Lpr lff">
    <q-header bordered class="bg-primary text-white">
      <q-toolbar class="q-px-xs">
        <div class="self-stretch row no-wrap">
          <q-btn self-stretch flat icon="menu" @click="showLeftDrawer=!showLeftDrawer"
            v-if="isApiUrlConfigured && !isConfigPage" />
        </div>
        <span class="q-ml-sm" v-if="(!isApiUrlConfigured || isConfigPage) && props.showHeaderLogo">&nbsp;</span>
        <q-avatar v-if="props.showHeaderLogo">
          <img :src="props.webHeaderLogo">
        </q-avatar>
        <q-toolbar-title>
          {{fx.packageInfo.productName}}
        </q-toolbar-title>
      </q-toolbar>
    </q-header>
    <q-drawer v-if="isApiUrlConfigured && !isConfigPage" v-model="showLeftDrawer" side="left" :width="260" content-class="bg-grey-1"
      elevated overlay behavior="mobile">
      <q-scroll-area style="height: calc(100% - 135px); margin-top: 90px;">
        <q-list>
          <template v-for="menuItem in sideMenuInfoFiltered">
            <q-expansion-item expand-separator v-if="Array.isArray(menuItem.children) && menuItem.children.length"
              :icon="menuItem.icon" :label="menuItem.label" :duration="200"
              :default-opened="checkIfNeedExpand(menuItem.children, route.path)" expand-icon="keyboard_arrow_down"
              :key="menuItem.id" group="sidemenu" :ref="menuItem.id">
              <q-item clickable active-class="text-primary text-weight-bold bg-grey-4" :to="subMenuItem.to"
                v-for="subMenuItem in menuItem.children" :key="subMenuItem.id" :ref="subMenuItem.id" dense>
                <q-item-section avatar class="q-ml-md">
                  <q-icon :name="subMenuItem.icon" />
                </q-item-section>
                <q-item-section>
                  {{ subMenuItem.label }}
                </q-item-section>
              </q-item>
            </q-expansion-item>
            <q-item v-else clickable exact exact-active-class="text-primary text-weight-bold bg-grey-4"
              :to="menuItem.to" :key="menuItem.id" :ref="menuItem.id">
              <q-item-section avatar>
                <q-icon :name="menuItem.icon" />
              </q-item-section>
              <q-item-section>
                {{ menuItem.label }}
              </q-item-section>
            </q-item>
          </template>
        </q-list>
      </q-scroll-area>
      <div v-if="isUserLogined" class="bg-primary text-white absolute-top" style="height: 90px">
        <div class="text-h6 q-pt-md text-center">{{fx.ua.value.displayName}}</div>
        <div class="text-subtitle2 q-pt-sm text-center">
          {{fx.rr.value.roleStr}}
          <q-btn dense flat icon="refresh" size="sm" title="刷新角色信息" :loading="refreshingRoleRightInfo"
            @click="refreshRoleRightInfo">
            <template v-slot:loading>
              <q-spinner />
            </template>
          </q-btn>
        </div>
      </div>
    </q-drawer>

    <q-page-container>
      <router-view />
    </q-page-container>
  </q-layout>
</template>

<script lang="ts">
export default {
  name: 'mainLayoutWmsPda'
}
</script>

<script lang="ts" setup>
import {SideMenuItem, UserRoleRightInfo, GenericStatus} from '@njt/foundation/defs/comm'
import {computed, onBeforeUnmount, PropType, ref} from 'vue'
import sideMenuInfoData from 'layouts/side-menu-info'
//@ts-ignore
import njtWebHeaderLogo from '@njt/foundation/assets/njt-web-header-logo.png'

const route = $f.router.currentRoute
const props = defineProps({
  webHeaderLogo: {
    type: String,
    default: njtWebHeaderLogo,
  },
  sideMenuInfo: {
    type: Array as PropType<SideMenuItem[]>,
    default: () => sideMenuInfoData,
  },
  showHeaderLogo: {
    type: Boolean,
    default: true,
  },
})

const showLeftDrawer = ref(false)
const refreshingRoleRightInfo = ref(false)

function checkIfNeedExpand(children: SideMenuItem[], path: string) {
  if (children) {
    for (const sideMenuItem of children) {
      if (sideMenuItem.to) {
        if (path.indexOf(sideMenuItem.to) === 0) {
          return true
        }
      }
    }
  }
  return false
}

function refreshRoleRightInfo() {
  refreshingRoleRightInfo.value = true
  $f.axios
    .get<UserRoleRightInfo>('comm/rr/get-my-role-right-info')
    .then((resp) => {
      if ($f.rr) {
        $f.rr.value = resp.data
      } else {
        $f.rr = ref(resp.data)
      }
      localStorage.setItem('rr', JSON.stringify(resp.data))
    })
    .catch((err) => {
      $f.ui.showNotifyFailed($f.getAxiosErrMsg(err))
    })
    .finally(() => {
      refreshingRoleRightInfo.value = false
    })
}

function updateUserGenericStatus() {
  if ($f.ua) {
    let userStateTimestamp = window.localStorage.getItem('userStateTimestamp')

    if ($f.router.currentRoute.value.meta.needLogin !== false) {
      $f.axios
        .get<GenericStatus>('/comm/auth/get-generic-status')
        .then((resp) => {
          const data = resp.data
          $f.isAppReadonly.value = data.isAppReadonly
          if ($f.unreadMsgNum) {
            $f.unreadMsgNum.value = data.unreadMsgNum
          } else {
            $f.unreadMsgNum = ref(data.unreadMsgNum)
          }
          window.localStorage.setItem('unreadMsgNum', $f.unreadMsgNum.value.toString())

          if (userStateTimestamp !== String(data.userStateTimestamp)) {
            window.localStorage.setItem('userStateTimestamp', data.userStateTimestamp.toString())
            refreshRoleRightInfo()
          }
        })
        .catch((err) => {
          console.error('获取用户通用状态出错: ' + $f.getAxiosErrMsg(err))
        })
    }
  }
}

const isApiUrlConfigured = computed(() => {
  return !!localStorage.getItem('apiUrl')
})

const isConfigPage = computed(() => {
  return '/wms/cfg/pda-config' === $f.router.currentRoute.value.name
})

const isUserLogined = computed(() => {
  return $f.ua
})

const sideMenuInfoFiltered = computed(() => {
  let result: SideMenuItem[] = []
  for (const sideMenuItem of props.sideMenuInfo) {
    if (Array.isArray(sideMenuItem.children) && sideMenuItem.children.length) {
      let children = []
      for (const subMenuItem of sideMenuItem.children) {
        if (!subMenuItem.needRight || $f.hasRight(subMenuItem.needRight)) {
          children.push(subMenuItem)
        }
      }
      if (children.length) {
        const newMenuItem = Object.assign({}, sideMenuItem)
        newMenuItem.children = children
        result.push(newMenuItem)
      }
    } else {
      if (!sideMenuItem.needRight || $f.hasRight(sideMenuItem.needRight)) {
        result.push(Object.assign({}, sideMenuItem))
      }
    }
  }
  return result
})

let genericStatusPooling = setInterval(() => {
  updateUserGenericStatus()
}, 60000)

updateUserGenericStatus()

onBeforeUnmount(() => {
  if (genericStatusPooling) {
    clearInterval(genericStatusPooling)
  }
})




const fx = $f
</script>

<style scoped>

</style>
